<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of DB
 *
 * @author Dmitry
 */
require_once './config/dbconfig.php';
class DBManager {
	
	protected $connection=null;
	protected $mysqli;
	public function __construct() {
		$this->connection = new mysqli($GLOBALS['dbhost'], $GLOBALS['dbusername'], $GLOBALS['dbpassword'], $GLOBALS['dbscheme']);
		if ($this->connection->connect_errno) {
			echo "Не удалось подключиться к MySQL: " . $this->connection->connect_error;
			throw new Exception("Не удалось подключиться к MySQL: " . $this->connection->connect_error);
		}
		if (!($this->connection->set_charset("utf8"))) 
		{
			printf("Ошибка при загрузке набора символов utf8: %s\n", $this->mysqli->error);
			throw new Exception("Ошибка при загрузке набора символов utf8: %s\n", $this->connection->error);
		}
		//$this->connection=$this->mysqli;
	}
	
	/**
	 * Создание нового плана покупок
	 * @param type $name название плана покапок
	 * @return type
	 */
	public function createPlan($name){
		$sql="insert into product_list_header (id, name, create_date, create_user_id, parent_list_id)"
					. "values (?,?,FROM_UNIXTIME(?),'admin',null)";
		$stmt=$this->connection->prepare($sql);
		$id=com_create_guid();
		$ct=time();
		$stmt->bind_param("ssi", $id,$name,$ct);
		if (!$stmt->execute()) {
			throw new Exception("Не удалось выполнить запрос: " . $this->connection->error);
		}
		$stmt->close();
		return $id;
	}
	/**
	 * Получить план по ID
	 * @param type $planid - id плана
	 * @return type
	 * @throws Exception
	 */
	public function getPlan($planid){
		$sql="select * from product_list_header where id=?";
		$stmt=$this->connection->prepare($sql);
		$id=$planid;
		$stmt->bind_param("s", $id);
		if (!$stmt->execute()) {
			throw new Exception("Не удалось выполнить запрос 1: " . $this->connection->error);
			
		}

		$plan_header= $stmt->get_result();
		$stmt->close();
		$plan_header=$plan_header->fetch_assoc();
		$sql="select d.id,d.product_id,d.unit,d.volume,p.name product,d.comment"
						. " from product_list_details d"
						. " inner join product p on p.id=d.product_id"
						. " where list_id=?"
						. " order by product";
		$stmt=$this->connection->prepare($sql);
		$stmt->bind_param("s", $id);
		if (!$stmt->execute()) {
			throw new Exception("Не удалось выполнить запрос: " . $this->connection->error);
			
		}
		$plan_details=$stmt->get_result();
		$stmt->close();
		$res = array('plan_header' => $plan_header,
					'plan_details' => $plan_details
		);
		return $res;
	}
	/**
	 * Получить все единицы измерения
	 * @return type
	 */
	public function getAllUnits() {
		$units = $this->connection->query("SELECT *"
							." FROM unit"
							." order by unit");
		return $units;
	}
	/**
	 * Получить все активыне продукты
	 * @return type
	 */
	public function getAllProducts() {
		$products = $this->connection->query("SELECT id,name,unit,volume_increment"
						." FROM product"
						." WHERE active=1"
						." order by name");
		return $products;
		
	}
	/**
	 * Получить все списки продкутов (все планы)
	 * @param type $active
	 * @return type
	 */
	public function getProductLists($active=1) {
		$res=$this->connection->query("SELECT *"
								. " FROM product_list_header"
								. " where active=".$active
								. " order by create_date desc");
		return $res;
	}
	
	public function createOrUpdateProduct($id,$unit,$name,$volume_increment){
		if ($id != "") {
			if (!$this->connection->query("update product set unit='" . $unit . "',name='" . $name
											. "',volume_increment=" . $volume_increment
											. " where id='" . $id . "'")) {
				throw new Exception($this->connection->errno . " " . $this->connection->error);
			}
		} else {
			$id = com_create_guid();
			if (!$this->connection->query("insert into product (id,name,unit,volume_increment) values('" . $id . "','"
											. $name . "','" . $unit . "'," . $volume_increment . ")")) {
				throw new Exception($this->connection->errno . " " . $this->connection->error);
			}
		}
		$res = array('status' => "ok",
		'recordId' => $_GET["id"],
		'record' => array(
		'id' => $_GET["id"],
		'name' => $_GET["name"],
		'volume_increment' => $_GET["volume_increment"],
		'unit' => $_GET["unit"])
		);
		return $res;
	}
}
